<template>
    <ElDialog v-model="dialogVisible" :title="dialogType === 'add' ? '添加员工' : '编辑员工'" width="30%" align-center>
        <ElForm ref="formRef" :model="formData" :rules="rules" label-width="100px">
            <ElFormItem label="姓名" prop="name">
                <ElInput v-model="formData.name" placeholder="请输入姓名" />
            </ElFormItem>
            <ElFormItem label="事业部" prop="department">
                <ElSelect v-model="formData.department" :filterable="true" :clearable="true" placeholder="请选择事业部">
                    <ElOption v-for="d in deptOptions" :key="d.value" :value="d.value" :label="d.label" />
                </ElSelect>
            </ElFormItem>
            <ElFormItem label="三级部门" prop="third_department">
                <ElSelect v-model="formData.third_department" :filterable="true" :clearable="true"
                    placeholder="请选择三级部门">
                    <ElOption v-for="d in thirdDeptOptions" :key="d.value" :value="d.value" :label="d.label" />
                </ElSelect>
            </ElFormItem>
            <ElFormItem label="类型" prop="type">
                <ElSelect v-model="formData.type" :filterable="true" :clearable="true" placeholder="请选择行业">
                    <ElOption v-for="op in staffOptions" :key="String(op.value)" :value="op.value" :label="op.label" />
                </ElSelect>
            </ElFormItem>
            <ElFormItem label="PM" prop="pm">
                <ElSelect v-model="formData.pm" placeholder="是否PM">
                    <ElOption label="是" value="Y" />
                    <ElOption label="否" value="N" />
                </ElSelect>
            </ElFormItem>
            <ElFormItem label="主管" prop="supervisor">
                <ElSelect v-model="formData.supervisor" :filterable="true" :clearable="true" placeholder="请选择主管">
                    <ElOption v-for="u in supervisorOptions" :key="String(u.id)" :value="u.id" :label="u.name" />
                </ElSelect>
            </ElFormItem>
            <ElFormItem label="是否主管" prop="is_supervisor">
                <ElSelect v-model="formData.is_supervisor" placeholder="是否主管">
                    <ElOption label="是" value="Y" />
                    <ElOption label="否" value="N" />
                </ElSelect>
            </ElFormItem>
            <ElFormItem label="行业" prop="industry">
                <ElSelect v-model="formData.industry" :filterable="true" :clearable="true" placeholder="请选择行业">
                    <ElOption v-for="op in industryOptions" :key="String(op.value)" :value="op.value"
                        :label="op.label" />
                </ElSelect>
            </ElFormItem>
        </ElForm>
        <template #footer>
            <div class="dialog-footer">
                <ElButton @click="dialogVisible = false">取消</ElButton>
                <ElButton type="primary" @click="handleSubmit">提交</ElButton>
            </div>
        </template>
    </ElDialog>
</template>

<script setup lang="ts">
import type { FormInstance, FormRules } from 'element-plus'
import { createStaff, updateStaff, type StaffResponse } from '@/api/system/staff'
import { useDictStore } from '@/store/modules/dict'
import { useSystemStore } from '@/store/modules/system'

interface Props {
    visible: boolean
    type: 'add' | 'edit'
    editData?: Partial<StaffResponse>
    departments?: Array<{ dept_code: string; dept_name: string }>
    thirdDepartments?: Array<{ dept_code: string; dept_name: string }>
}

interface Emits {
    (e: 'update:visible', value: boolean): void
    (e: 'submit'): void
}

const props = defineProps<Props>()
const emit = defineEmits<Emits>()
const dict = useDictStore()
const system = useSystemStore()

// 下拉选项
const deptOptions = computed(() => (props.departments || []).map((d) => ({ label: d.dept_name, value: d.dept_code })))
const thirdDeptOptions = computed(() => (props.thirdDepartments || []).map((d) => ({ label: d.dept_name, value: d.dept_code })))
const industryOptions = computed(() => dict.getOptions('industry'))
const staffOptions = computed(() => dict.getOptions('staff'))
const supervisorOptions = computed(() => system.getSalers.filter((u) => u.is_supervisor !== 'N'))

// 对话框显示控制
const dialogVisible = computed({
    get: () => props.visible,
    set: (val) => emit('update:visible', val)
})

const dialogType = computed(() => props.type)

// 表单实例
const formRef = ref<FormInstance>()

// 表单数据
const formData = reactive({
    name: '',
    department: '',
    type: '',
    pm: '',
    status: '',
    supervisor: '',
    is_supervisor: 'N',
    third_department: '',
    industry: ''
})

// 校验规则
const rules: FormRules = {
    name: [{ required: true, message: '请输入姓名', trigger: 'blur' }],
    department: [{ required: true, message: '请选择事业部', trigger: 'change' }],
    type: [{ required: true, message: '请输入类型', trigger: 'blur' }],
    pm: [{ required: true, message: '请输入PM', trigger: 'blur' }],
    status: [{ required: true, message: '请输入状态', trigger: 'blur' }],
    supervisor: [{ required: true, message: '请输入主管', trigger: 'blur' }],
    third_department: [{ required: true, message: '请选择三级部门', trigger: 'change' }]
}

// 初始化表单
const initFormData = () => {
    const isEdit = props.type === 'edit' && props.editData
    const row = props.editData || {}
    Object.assign(formData, {
        name: isEdit ? (row.name || '') : '',
        department: isEdit ? (row.department || '') : '',
        type: isEdit ? (row.type || '') : '',
        pm: isEdit ? (row.pm || '') : '',
        status: isEdit ? (row.status || '') : '',
        supervisor: isEdit ? (row.supervisor || '') : '',
        is_supervisor: isEdit ? (row.is_supervisor || 'N') : 'N',
        third_department: isEdit ? (String(row.third_department || '')) : '',
        industry: isEdit ? (row.industry || '') : ''
    })
}

watch(
    () => [props.visible, props.type, props.editData],
    async ([visible]) => {
        if (visible) {
            // 确保行业字典已加载（若未预加载）
            try {
                await dict.ensure(['industry'], { ttlMs: 10 * 60 * 1000 })
            } catch (e) {
                console.warn('行业字典加载失败：', e)
            }
            initFormData()
            nextTick(() => formRef.value?.clearValidate())
        }
    },
    { immediate: true }
)

// 提交
const handleSubmit = async () => {
    if (!formRef.value) return
    await formRef.value.validate(async (valid) => {
        if (!valid) return

        const payload = {
            name: formData.name,
            department: formData.department,
            type: formData.type,
            pm: formData.pm,
            status: formData.status,
            supervisor: formData.supervisor,
            is_supervisor: formData.is_supervisor || 'N',
            third_department: formData.third_department,
            industry: formData.industry
        }

        try {
            if (dialogType.value === 'add') {
                await createStaff(payload)
            } else {
                const id = Number(props.editData?.id)
                if (!id) {
                    ElMessage.error('缺少员工ID，无法编辑')
                    return
                }
                await updateStaff(id, payload)
            }
            ElMessage.success('提交成功')
            emit('submit')
        } catch (error) {
            console.error('提交失败:', error)
            ElMessage.error('提交失败，请稍后重试')
        }
    })
}
</script>

<style lang="scss" scoped>
.dialog-footer {
    display: flex;
    justify-content: flex-end;
}
</style>